import { defineStore } from "pinia";
import {
  fetchCartItems,
  updateCartItem,
  deleteCartItem
} from "../api/cart";

const mapCartItem = item => {
  if (!item) return null;
  const snapshot = item.snapshot_attrs || item.snapshot || {};
  return {
    id: item.id,
    productId: item.product_id || item.productId,
    name: snapshot.title || item.title || "未命名商品",
    model: snapshot.model || item.model || "-",
    qty: Number(item.qty ?? 0),
    unit: snapshot.unit || item.unit || "件",
    status: item.status,
    remark: item.remark || "",
    price: Number(item.snapshot_price ?? 0),
    currency: item.snapshot_currency || "CNY",
    snapshot,
    createTime: item.create_time,
    updateTime: item.update_time
  };
};

export const useCartStore = defineStore("buyer-cart", {
  state: () => ({
    items: [],
    loading: false,
    error: null
  }),
  getters: {
    totalQty: state => state.items.reduce((sum, item) => sum + item.qty, 0),
    amountSummary: state =>
      state.items.reduce((sum, item) => sum + item.qty * item.price, 0)
  },
  actions: {
    async load() {
      this.loading = true;
      this.error = null;
      try {
        const { data } = await fetchCartItems({ page_size: 100 });
        const payload = data?.data || data || {};
        const list = payload.list || payload.items || [];
        this.items = list.map(mapCartItem).filter(Boolean);
      } catch (error) {
        this.error = error.message || "购物车加载失败";
        throw error;
      } finally {
        this.loading = false;
      }
    },
    async updateQty(id, qty) {
      await updateCartItem(id, { qty });
      const target = this.items.find(item => item.id === id);
      if (target) {
        target.qty = qty;
      }
    },
    async remove(id) {
      await deleteCartItem(id);
      this.items = this.items.filter(item => item.id !== id);
    },
    clear() {
      this.items = [];
      this.error = null;
    }
  }
});
